<?php

class Core_Helper_Permission_Helper {

    public function getRolesByArea($code) {
        return App::getModel('permission/collection_role')
                    ->eq('code', ':code')
                    ->addParameter('code', $code)
                    ->load();
    }

    public function getRoleIdsByCodes(array $codes){
        return App::getModel('permission/collection_role')
                ->contain('code', ':codes:s')
                ->addParameter('codes', $codes)
                ->load()
                ->getItemPropertyValue('id');
    }

//    public function getResources($areaId, $type) {
//        return App::getModel('permission/collection_resource')
//                ->where()
//                ->eq('area_id', ':areaId:i')
//                ->eq('type', ':type:s')
//                ->closest()
//                ->adaParameter(array('areaId' => $areaId, 'type' => $type))
//                ->load();
//    }

    public function allowAccessComponent($component = NULL, $controller = NULL, $action = NULL) {
        $component = is_null($component) ? Kd_Web::getRouter()->getComponent() : $component;
        $controller = is_null($controller) ? Kd_Web::getRouter()->getController() : $controller;
        $action = is_null($action) ? Kd_Web::getRouter()->getAction() : $action;
        $list = App::getModel('permission/collection_accredit_action')
                        ->where()
                        ->eq('component_name', "'$component'")
                        ->eq('area_id', App::getAreaSetting()->getId())
                        ->closest()
                        ->load();
        if (count($list) > 0) {
            foreach ($list as $item) {
                if ($item->getControllerName() == '*' || $item->getControllerName() == $controller) {
                    if ($item->getActionName() == '*' || $item->getActionName() == $action) {
                        $result = $item->allowAccess(Kd_Web::getIdentity());
                        if (!$result) {
                            return FALSE;
                        }
                    }
                }
            }
        }
        return TRUE;
    }

}